package com.cat.dataStructure;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
*   @description https://leetcode.cn/problems/merge-intervals/description/
*   @author 曲大人的喵
*   @create 2025/8/23 16:09
*   @since JDK17
*/
public class Solution48 {
    public int[][] merge(int[][] intervals) {
        int n = intervals.length;
        Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);
        List<int[]> list = new ArrayList<>();
        for (int i = 0, j; i < n; ) {
            j = i + 1;
            while (j < n && intervals[i][1] >= intervals[j][0]) {
                intervals[i][1] = Math.max(intervals[i][1], intervals[j++][1]);
            }
            list.add(new int[]{intervals[i][0], intervals[i][1]});
            i = j;
        }
        int[][] ans = new int[list.size()][2];
        for (int i = 0; i < list.size(); i++) {
            ans[i] = list.get(i);
        }

        return ans;
    }
}
